<?php
namespace includes;

/**
 * Class for connection to and perform queries on a Mysql Database
 *
 * @author John Sterken
 */
class MysqlDatabase implements Database{
    private $connection;
    public  $last_query;
    private $magic_quotes_active;
    private $real_escape_string_exists;
    
    /**
     * Constructor
     * Opens connection and checks if magic quotes is active and if we can use mysql_real_escape_string.
     */
    public function __construct() {
	$this->open_connection();
	$this->magic_quotes_active = get_magic_quotes_gpc();
	$this->real_escape_string_exists = function_exists( "mysql_real_escape_string" );
    }
    public function open_connection() {
	$this->connection = mysql_connect( DB_HOST, DB_USER, DB_PASS );
	if(!$this->connection) {
	    die("Connection failed ".  mysql_error());
	}
	else {
	    $usedDatabase = mysql_select_db( USED_DATABASE );
	    if(!$usedDatabase)
		die("Database selection failed ".  mysql_error());
	}
    }
    public function close_connection() {
	if(isset($this->connection)) {
		mysql_close($this->connection);
		unset($this->connection);
	}
    }
    public function escape_value( $value ) {
	if($this->real_escape_string_exists) { //php 4.3 and higher
	    if($this->magic_quotes_active) 
		$value = stripslashes ( $value );
	    
	    $value = mysql_real_escape_string ( $value );
	}
	elseif(!$this->magic_quotes_active) { //php 4.3 or lower
		$value = addslashes ( $value );
	}
	    
	return $value;
    }
    public function query( $sql ) {
	$this->last_query = $sql;
	
	$result = mysql_query($sql, $this->connection);
	$this->confirm_query($result);
	
	return $result;
    }
    public function num_rows($result) {
	return mysql_num_rows($result);
    }
    public function fetch_array($result) {
	return mysql_fetch_array($result);
    }
    public function insert_id() {
	return mysql_insert_id($this->connection);
    }
    public function affected_rows() {
	return mysql_affected_rows($this->connection);
    }
    public function confirm_query($result) {
	if(!$result)
	    die("query failed". mysql_error());
    }
}

$database = new MysqlDatabase();
?>
